package com.zf.museum.service.impl;

import com.zf.museum.bean.GetResult;
import com.zf.museum.bean.Msg;
import com.zf.museum.bean.Question;
import com.zf.museum.bean.Result;
import com.zf.museum.model.*;
import com.zf.museum.repository.*;
import com.zf.museum.service.RecordService;
import com.zf.museum.service.TfngService;
import com.zf.museum.service.WrongService;
import com.zf.museum.utils.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Service
public class TfngServiceImpl implements TfngService{

    @Autowired
    private TfngRepository tfngRepository;
    @Autowired
    private WrongService wrongService;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RecordService recordService;
    @Autowired
    private RecordRepository recordRepository;

    @Override
    public Result upload(MultipartFile file) {

        Result result = GetResult.fail();
        List<Tfng> tfngs = new ArrayList<>();
        String fileName = file.getOriginalFilename();

        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            result.setMsg("上传文件格式错误");
            return result;
        }

        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }

        InputStream is = null;
        Workbook wb = null;
        try {
            is = file.getInputStream();
            if (isExcel2003) {
                wb = new HSSFWorkbook(is);
            } else {
                wb = new XSSFWorkbook(is);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        Sheet sheet = wb.getSheetAt(0);
        if(sheet == null){
            result.setMsg("导入失败,上传文本为空");
            return result;
        }

        Tfng tfng = null;
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            //每行
            Row row = sheet.getRow(r);
            //每个单元格
            Cell cell = null;
            if (row == null){
                continue;
            }
            /*提取题目内容*/
            cell = row.getCell(0);
            String content = ExcelUtil.getCellValue(cell);
            if(content == null || content.isEmpty()){
                result.setMsg("导入失败，第"+(r+1)+"行中题目内容为空");
                return result;
            }
            /*获取答案*/
            cell = row.getCell(1);
            String answer = ExcelUtil.getCellValue(cell);

            tfng = new Tfng();
            tfng.setAnswer(answer);
            tfng.setContent(content);
            tfngs.add(tfng);
        }

        try {
            tfngRepository.saveAll(tfngs);
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }

        return GetResult.success();
    }

    @Override
    public List<Tfng> findAll() {

        return tfngRepository.findAll();
    }

    @Override
    public Result update(List<Tfng> tfngs) {

        try {
            tfngRepository.saveAll(tfngs);
        } catch (Exception e) {
            e.printStackTrace();
            return GetResult.fail();
        }
        return GetResult.success();
    }

    @Override
    @Transactional
    public Result delete(List<Long> ids) {

        try {
            for (Long id: ids
                 ) {
                tfngRepository.deleteById(id);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return GetResult.fail();
        }
        return GetResult.success();
    }

    @Override
    public boolean judge(Question question) {

        String openId = question.getOpenId();
        /*根据题号获取题目*/
        Tfng tfng = tfngRepository.getOne(question.getId());
        boolean b = true;
        /*判断答题对错*/
        if (!question.getAnswers().get(0).equals(tfng.getAnswer())) {
            wrongService.addTfng(tfng, openId);
            b = false;
        } else {
            /*保存答对题目的记录*/
            recordService.addTfng(tfng, openId);
        }

        return b;
    }

    @Override
    public List<Tfng> getTfngs(String openId) {

        User user = userRepository.getUserByOpenId(openId);
        List<Tfng> record = recordRepository.getTfng(user);
        List<Tfng> all = tfngRepository.findAll();
        List<Tfng> tfngs = new ArrayList<>();
        int count = 0;
        int size = all.size();
        while(true) {
            /*随机获取*/
            Random random = new Random();
            int a = random.nextInt(size);
            Tfng tfng = all.get(a);
            if (!record.contains(a) && count < 6) {
                tfngs.add(tfng);
                count++;
                if (count == 6) {
                    break;
                }
            }
        }

        return tfngs;
    }
}
